package com.gitee.feizns.explore.data_structure.tree.bs.easy;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 501. 二叉搜索树中的众数
 * @author feizns
 * @since 2019/12/31
 */
public class FindMode {

    public static void main(String[] args) {
        int[] mode = findMode(create());
        System.out.println(Arrays.toString(mode));
    }

    private static TreeNode create() {
        TreeNode ret = new TreeNode(6);
        ret.left = new TreeNode(2);
        ret.left.left = new TreeNode(0);
        ret.left.right = new TreeNode(4);
        ret.left.right.left = new TreeNode(2);
        ret.left.right.right = new TreeNode(6);
        ret.right = new TreeNode(8);
        ret.right.left = new TreeNode(7);
        ret.right.right = new TreeNode(9);
        return ret;
    }

    public static int[] findMode(TreeNode root) {
        if ( root != null ) {
            Map<Integer, Integer> maps = new HashMap<>();
            statistics(maps, root);
            Integer max = Collections.max(maps.values());
            List<Integer> ret = new LinkedList<>();
            for (Map.Entry<Integer, Integer> entry : maps.entrySet()) {
                if ( entry.getValue().equals(max) )
                    ret.add(entry.getKey());
            }
            return ret.stream().mapToInt(Integer::intValue).toArray();
        }
        return new int[]{};
    }

    private static void statistics(Map<Integer, Integer> statistics, TreeNode node) {
        if ( node != null ) {
            Integer num = statistics.get(node.val);
            num = num == null ? 1 : num + 1;
            statistics.put(node.val, num);
            statistics(statistics, node.left);
            statistics(statistics, node.right);
        }
    }

}
